//
//  HistorySettleController.m
//  ScalperMerchant
//
//  Created by 王云 on 2017/12/4.
//  Copyright © 2017年 WY. All rights reserved.
//

#import "HistorySettleController.h"
#import "HistorySettView.h"
#import "DataPickView.h"
#import "HistorySettCell.h"
#import "SettlementDetailController.h"

@interface HistorySettleController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,weak)HistorySettView *headerV;
@property (nonatomic,weak)UITableView *tableView;
@property (nonatomic,strong)DataPickView *infoView;

@property (nonatomic,copy)NSString *statStr;
@property (nonatomic,copy)NSString *endStr;

@property (nonatomic,strong)NSMutableArray *billData;
@property (nonatomic, assign) NSInteger PageNumber;
@property (nonatomic,strong)NSNumber *totalCountKey;

@end

@implementation HistorySettleController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"历史结算单";
    [self setUI];
    
    [self loadData];
    [self loadReferView];
}
- (void)loadData{
    
    _PageNumber = 1;
    __weak __typeof(&*self)weakSelf = self;
    [SCApiTool ScBillStartTime:@"" endTime:@"" CurPage:_PageNumber pageSize:12 success:^(NSDictionary *data) {
        weakSelf.totalCountKey = [data hw_safeObjectForKey:@"count_page"];
        NSArray *bill = [data hw_safeObjectForKey:@"data_list"];
        [weakSelf.headerV.billNumL hw_setAttributedText:[NSString stringWithFormat:@"账单总数：<style font=16 color=#fd6c40>%@</style>",data[@"count"]]];
        if (bill.count == 0) {
            [SCTool showMessage:@"暂无数据"];
        }
        weakSelf.billData = bill.mutableCopy;
        [weakSelf performSelector:@selector(setBillData:) withObject:_billData];
        [weakSelf.tableView reloadData];
    } failure:^(NSString *errormsg) {
         [SCTool showError:errormsg];
    }];
   
}
- (void)loadReferView
{
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
- (void)loadMoreData{
    _PageNumber++;
    if ([_totalCountKey integerValue]< _PageNumber) {
        [SCTool showMessage:@"没有更多数据"];
        [_tableView.mj_footer endRefreshing];
        _PageNumber--;
        return ;
    }
    __weak __typeof(&*self)weakSelf = self;
    if (_statStr.length == 0) {
        
        [SCApiTool ScBillStartTime:@"" endTime:@"" CurPage:_PageNumber pageSize:12 success:^(NSDictionary *data) {
            
            [weakSelf.billData addObjectsFromArray:[data hw_safeObjectForKey:@"data_list"]];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView.mj_footer endRefreshing];
            
        } failure:^(NSString *errormsg) {
            [SCTool showError:errormsg];
            [weakSelf.tableView.mj_footer endRefreshing];
        }];
        return;
    }
    [SCApiTool ScBillStartTime:_statStr endTime:_endStr CurPage:_PageNumber pageSize:12 success:^(NSDictionary *data) {
        
        [weakSelf.billData addObjectsFromArray:[data hw_safeObjectForKey:@"data_list"]];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_footer endRefreshing];
        
    } failure:^(NSString *errormsg) {
        [SCTool showError:errormsg];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)setUI{
    __weak __typeof(&*self)weakSelf = self;
    HistorySettView *headerV = [[[NSBundle mainBundle] loadNibNamed:@"HistorySettView" owner:self options:nil] lastObject];
    [headerV.billNumL hw_setAttributedText:[NSString stringWithFormat:@"账单总数：<style font=14 color=#fd6c40>%@</style>",@"15"]];
    headerV.click = ^(HistorySBtnType type) {
        switch (type) {
            case start:
            {
                [weakSelf show:@"start"];
            }
                break;
            case end:
            {
                [weakSelf show:@"end"];
            }
                break;
            case yes:
            {
                [weakSelf timeData];
            }
                break;
            default:
                break;
        }
    };
    [self.view addSubview:headerV];
    _headerV = headerV;
    
    [headerV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf.view);
        make.height.equalTo(@100);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(weakSelf.view);
        make.top.equalTo(headerV.mas_bottom).offset(8);
    }];
}
- (void)timeData{
    
    DLog(@"%@----%@",_statStr,_endStr);
    DLog(@"%@",[HWCommon getTimeData:_statStr]);
    DLog(@"%@",[HWCommon getTimeData:_endStr]);
    
    if (_statStr == nil ) {
        [SCTool showError:@"开始日期未选择"];
        return;
    }
    if (_endStr == nil) {
        [SCTool showError:@"结束日期未选择"];
        return;
    }

    
    int pare = [HWCommon compareOneDay:[HWCommon getTimeData:_statStr] withAnotherDay:[HWCommon getTimeData:_endStr]];
    if (pare == 1) {
        [SCTool showError:@"日期有误"];
        return;
    }
    _PageNumber = 1;
    __weak __typeof(&*self)weakSelf = self;
    [SCApiTool ScBillStartTime:_statStr endTime:_endStr CurPage:_PageNumber pageSize:12 success:^(NSDictionary *data) {
        weakSelf.totalCountKey = [data hw_safeObjectForKey:@"countPage"];
        NSArray *bill = [data hw_safeObjectForKey:@"data_list"];
        if (bill.count == 0) {
            [SCTool showMessage:@"暂无数据"];
        }else{
            [SCTool showMessage:@"查询成功"];
        }
        weakSelf.billData = bill.mutableCopy;
        [weakSelf performSelector:@selector(setBillData:) withObject:_billData];
        [weakSelf.tableView reloadData];
    } failure:^(NSString *errormsg) {
        [SCTool showError:errormsg];
    }];
}
- (void)setBillData:(NSMutableArray *)billData{
    _billData = billData;
    if ([_billData count] < 12) {
        self.tableView.mj_footer.hidden = YES;
    }else{
        [self.tableView.mj_footer setHidden:NO];
    }
}

#pragma mark - pickView Show
- (void)show:(NSString *)title{
    __weak __typeof(&*self)weakSelf = self;
    _infoView = [[DataPickView alloc] initWithFrame:CGRectMake(0, KHeight, kWidth, 220)];
    _infoView.types = @"date";
    _infoView.btnStr = title;
    _infoView.voice = ^(NSString *Invoice) {
        NSString *timeStr = [HWCommon getTimeStamp:Invoice];
        NSArray *timeArr = [Invoice componentsSeparatedByString:@" "];
        
        if ([title isEqualToString:@"start"]) {
            [weakSelf.headerV.startBtn setTitle:[NSString stringWithFormat:@"%@",timeArr[0]] forState:UIControlStateNormal];
            weakSelf.statStr = timeStr;
            
        }else{
            weakSelf.endStr = timeStr;
            [weakSelf.headerV.endBtn setTitle:[NSString stringWithFormat:@"%@",timeArr[0]] forState:UIControlStateNormal];
            
        }
    };
    [_infoView show];
}
#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.billData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HistorySettCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HistorySettCell" forIndexPath:indexPath];
    cell.item = self.billData[indexPath.section];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SettlementDetailController *DetailVC = [[SettlementDetailController alloc] init];
    NSDictionary *item = self.billData[indexPath.section];
    DetailVC.bill_id = [NSString stringWithFormat:@"%@",item[@"bill_id"]];
    [self.navigationController pushViewController:DetailVC animated:yes];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 2;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
     return [UIView new];
}
- (UITableView *)tableView{
    
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.rowHeight = 95;
        tableView.separatorColor = WYColor(238, 238, 238);
        tableView.tableFooterView = [[UIView alloc] init];
        [tableView registerNib:[UINib nibWithNibName:@"HistorySettCell" bundle:nil] forCellReuseIdentifier:@"HistorySettCell"];
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
